package ldh.im.fxbase.richtext;

import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import ldh.im.fxbase.controller.ImagePageController;
import ldh.im.fxbase.util.RegionUtil;

public class ImageTextItem extends TextItem<ImageTextItem> {

    private String imgUri;

    public ImageTextItem(String imgUri) {
        this.imgUri = imgUri;
    }

    public Node createNode() {
        try {
            ImageView imageView = new ImageView();
            imageView.setImage(new Image(imgUri));
            if (imageView.getImage().getWidth() > 290) {
                imageView.setFitWidth(290);
//                imageView.setScaleX(290/imageView.getImage().getWidth());
            }
            if (imageView.getImage().getHeight() > 100) {
                imageView.setFitHeight(100);
//                imageView.setScaleY(100/imageView.getImage().getHeight());
            }
            imageView.setOnMouseClicked(e->{
                if (e.getClickCount() != 2) return;
                Stage stage = new Stage();
                RegionUtil.FxmlBean<VBox, ImagePageController> node = RegionUtil.loadFxmlBean(this.getClass().getResource("/fxmls/ImagePage.fxml"));
                node.getController().setImage(new Image(imgUri));
                Scene scene = new Scene(node.getNode());
                stage.setScene(scene);
                stage.show();
            });
            return imageView;
        } catch (Exception e) {
            return new Label("图片不存在");
        }
    }

    public TextItemType getTextItemType() {
        return TextItemType.image;
    }

    public String getImgUri() {
        return imgUri;
    }

    @Override
    public boolean isNull() {
        if (imgUri == null || imgUri.trim().equals("")) {
            return true;
        }
        return false;
    }

    @Override
    public String getData() {
        return getImgUri();
    }

   public static String parseUrl(String content) {
        String result = content;
        if (content.startsWith(TextItem.SPLIT_STRING) && content.endsWith(TextItem.SPLIT_STRING)) {
            result = content.substring(TextItem.SPLIT_STRING.length(), content.length() - TextItem.SPLIT_STRING.length());
            String pre = TextItemType.image.name();
            if (result.startsWith(pre)) {
                return result.substring(pre.length() + 1);
            }
        }
        return null;
    }

    public static String format(String content) {
        return TextItem.SPLIT_STRING + TextItemType.image.name() + ":" + content + TextItem.SPLIT_STRING;
    }
}
